<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="list" style="display:flex ; text-align:center;"></div>
    <button class="prev">上一页</button>
    <button class="next">下一页</button>
    <span class="num"></span>
</body>

</html>

<script>

    //保存页码
    let page = 1;

    //将对象格式转为字符串
    function objToSearchString(obj) {
        var str = '';
        for (var key in obj) {
            str += `${key}=${obj[key]}&`
        }
        return str.slice(0, str.length - 1);
    }
    //封装发送ajax请求
    function ajax(method, url, params, cb) {
        //1.创建一个xhr对象
        var xhr = new XMLHttpRequest();
        //2.配置xhr对象
        xhr.open(method, url + "?" + objToSearchString(params));
        //3.设置回调函数, 用来接收返回的响应数据
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                cb(JSON.parse(xhr.responseText));
            }
        }
        //4.发送请求
        xhr.send();
    }

    //封装请求数据
    function getajax(pageStatus) {
        ajax('get', `https://yantianfeng.com/api/emotion`, { page: pageStatus, count: 10 }, function (data) {
            var str = data.emotions.map((item, index) => {
                return `<div> <img src="${item.url}" /> <div> ${item.title} </div> </div>`
            }).join('')
            document.querySelector('.list').innerHTML = str;
        });
    }

    //默认上一页按钮禁用
    document.querySelector('.prev').disabled = true
    //默认显示第一页的10个表情
    if (document.querySelector('.prev').disabled) {
        getajax(page);
    }


    //点击上一页, 获取上一页的表情并渲染
    document.querySelector('.prev').onclick = function () {
        document.querySelector('.next').disabled = false
        document.querySelector('.num').innerHTML = `${page - 1}/4`
        if (page > 1) {
            getajax(--page);
        }
        //如果是第一页，禁用上一页按钮
        if (page == 1) {
            document.querySelector('.prev').disabled = "true"
        }
    }

    //点击下一页, 获取下一页的表情并渲染
    document.querySelector('.next').onclick = function () {
        document.querySelector('.prev').disabled = false
        document.querySelector('.num').innerHTML = `${page + 1}/4`
        if (page < 4) {
            getajax(++page);
        }
        //如果是最后一页，禁用下一页按钮
        if (page == 4) {
            document.querySelector('.next').disabled = true
        }

    }
</script>